package com.xjcs.saplingplan.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.xjcs.saplingplan.dialog.LoadingDialog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseVbFragment<VB : ViewBinding> : Fragment() {

    lateinit var mBinding: VB

    private var loadingDialog: LoadingDialog? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = getViewBinding()
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        registerObserver()
        initUi()
        initListener()
    }

    abstract fun getViewBinding(): VB

    abstract fun initUi()

    /**
     * 创建LiveData数据观察者
     */
    abstract fun registerObserver()

    /**
     * 点击事件
     */
    abstract fun initListener()

    /**
     * 默认的事件处理方法
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEvent(event: Any) {
        // 子类可以重写此方法以处理特定事件
    }

    /**
     * isAdded
     * 检查Fragment是否已经添加到Activity中。如果Fragment未添加到Activity，则不应该显示LoadingDialog。
     *
     * isRemoving
     * 检查Fragment是否正在被移除。如果Fragment正在被移除，则不应该显示LoadingDialog。
     */
    fun showLoading() {
        if(isAdded && !isRemoving && loadingDialog == null){
            loadingDialog = LoadingDialog(requireContext())
        }
        if(isAdded && !isRemoving){
            loadingDialog?.show()
        }
    }

    fun hideLoading() {
        if(isAdded && !isRemoving){
            loadingDialog?.dismiss()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //防止内存泄露
        loadingDialog?.dismiss()
        loadingDialog = null
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        hideLoading() // 在Fragment不可见时关闭加载框
    }

    override fun onPause() {
        super.onPause()
        hideLoading() // 在Fragment不可见时关闭加载框
    }

}